//
//  LoopStatusDAL.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/30.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit

class LoopStatusDAL: NSObject {

    class func loadHomeData(since_id:Int64 ,max_id:Int64,isPull:Bool,finish:@escaping ([[String:Any]]?)->()){
    
        //先判断是否有本地缓存数据
        let res = checkOutCaches(since_id: since_id, max_id: max_id)
        
        if let result = res,result.count > 0{
        
            finish(result)
            return
        }
        
        //没有的话加载网络请求
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"

        let parameters = ["access_token" : LoopUserAccountViewModel.shared.access_token,
                          "max_id" : "\(max_id)",
            "since_id" : "\(since_id)"]
        LoopNetWorkManager.shared.request(HTTPMethod: .GET, urlString: urlString, parameters: parameters, finish: {(respondsObject,error)->() in

            if error != nil {
                finish(nil)
            }
            
            let dic = respondsObject as! [String:Any]
            guard let array = dic["statuses"] as? [[String : Any]] else{
            
                finish(nil)
                return
            }
            finish(array)

            cacheHomeData(array: array)
            let resCount = checkOutCaches(since_id: 0, max_id: 0)
            if let resultCount = resCount,resultCount.count >= 20{
                deleteOldData()
            }
            
        })
    
    }
    
    class func checkOutCaches(since_id:Int64 ,max_id:Int64)->([[String:Any]]?){
        
        guard let userId = LoopUserAccountViewModel.shared.userAccount?.uid else {
            return nil
        }
        var sql = "SELECT * FROM t_Weibo WHERE userId = \(userId) "

        if since_id > 0 {
            //向上查找
            sql += "AND statusId > \(since_id) "
        }
        
        if max_id > 0 {
            //向上查找
            sql += "AND statusId < \(max_id) "
        }
        
        //排序 降序
        sql += "ORDER BY statusId DESC "
        
        var array = [[String:Any]]()
        
        LoopFMDBManager.shared.queue.inDatabase { (db) in
            guard let res = db!.executeQuery(sql, withArgumentsIn: nil) else {
                //在闭包中不能够return
                return
            }
            //逐条获取数据
            while res.next() {
                //获取status 二进制数据
                let jsonData = res.data(forColumn: "status")
                //转换为json 字典
                let dict = try! JSONSerialization.jsonObject(with:jsonData!, options: [])
                array.append(dict as! [String : Any])
            }
        }
        
        return array
    }
        
    class func cacheHomeData(array:[[String:Any]]){
        guard let userId = LoopUserAccountViewModel.shared.userAccount?.uid else {
            return
        }
        
        let sql = "INSERT OR REPLACE INTO t_Weibo (statusId,status,userId) VALUES (?,?,?)"
        
        LoopFMDBManager.shared.queue.inTransaction { (db, rollback) in
            for item in array{
            
                let statusId = item["id"]!
                
                let JSONData = try! JSONSerialization.data(withJSONObject: item, options: [])
                
                let res = db!.executeUpdate(sql, withArgumentsIn: [statusId,JSONData,userId])
                if !res{
                
                    rollback?.pointee = true
                }
            }
        }
    }
    
    
    class func deleteOldData(){
        guard let userId = LoopUserAccountViewModel.shared.userAccount?.uid else {
            return
        }
        
        let sql = "delete from t_Weibo where statusId in (select statusId from t_Weibo order by statusId desc limit 20,20) AND userId = \(userId)"
        
        LoopFMDBManager.shared.queue.inDatabase { (db) in
            db?.executeStatements(sql)
        }
    
    }
}
